﻿using Daemon.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Daemon.Data.Infrastructure.Auth
{
    public class AuthInfoEF : BaseAuthInfo
    {
        public AuthInfoEF()
        {
        }

        public AuthInfoEF(BaseAuthUser user)
        {
            UserEntity = user;
            UserId = user.Id;
            UserName = user.UserName;
            if (user.UserType != "WX")
            {
                AuthorizationTree = GetAuthInfoFromUser(user);
            }
        }

        private JObject GetAuthInfoFromUser(BaseAuthUser user)
        {
            JObject authTree = AuthInfoHelper.BulidAuthTree(user);

            JObject securedItems = (JObject)authTree["securedItems"];
            JObject securedGroupedItems = (JObject)authTree["securedGroupedItems"];

            if (AuthInfoHelper.IsAdministrator(UserEntity))
            {
                IsAdmin = true;
                return authTree;
            }

            IEnumerable<AdminRole> roleData = user.UserRoles != null && user.UserRoles.Any() ? user.UserRoles?.Select(u => u.AdminRole) : user.Roles?.Select(u => u);

            if (roleData == null)
            {
                return authTree;
            }

            foreach (AdminRole roleEntity in roleData)
            {
                AuthInfoHelper.UpdateSecuredItemsRelated(securedItems, securedGroupedItems, roleEntity.RoleSecuredItems);
            }

            return authTree;
        }
    }
}
